package io.grpc.internal;

import io.grpc.ServerCall;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

public class ServerStreamHelper {

    private final static VarHandle SERVER_STREAM_HANDLE;

    static {
        try {
            SERVER_STREAM_HANDLE = MethodHandles.privateLookupIn(ServerCallImpl.class, MethodHandles.lookup()).findVarHandle(ServerCallImpl.class, "stream", ServerStream.class);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


    public static ServerStream getServerStream(final ServerCall<?, ?> call) {
        if (call instanceof ServerCallImpl serverCallImpl) {
            return (ServerStream) SERVER_STREAM_HANDLE.get(serverCallImpl);
        }

        throw new UnsupportedOperationException();
    }
}
